import { checkAuth } from '/store/actions'
import { $event } from '/utils'
import { GlobalData } from '/store/state'
import { userApi } from '/api/user'

Page({
  data: {
    type: '',
    loading: false,
    followingQuery: {
      limit: 20,
      offset: 0,
    },
    followerQuery: {
      limit: 20,
      offset: 0,
    },
    inviteeQuery: {
      limit: 20,
      offset: 0,
    },
    followers: [] as DomoUser[],
    followings: [] as DomoUser[],
    invitee: [] as DomoUser[],
    followerCanLoad: true,
    followingCanLoad: true,
    inviteeCanLoad: true,
    navigationHeight: 0,
  },
  async onLoad({ type, hasfolling }: any) {
    this.setData({
      type,
      navigationHeight: GlobalData.navigationHeight,
    }),
      $event.on('after:login', this, async () => {
        this.onPullDownRefresh()
      })
    if (hasfolling) {
      userApi.setReaded('following')
      $event.emit('cancelRedDot')
    }
    await checkAuth()
    this.onPullDownRefresh()
  },
  onReachBottom() {
    this.fetchUsers(true)
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    const {
      data: { type },
    } = this
    let queryType = 'followingQuery'
    if (type === 'follower') {
      queryType = 'followerQuery'
    }
    if (type === 'invitee') {
      queryType = 'inviteeQuery'
    }
    this.setData(
      {
        [queryType]: {
          limit: 20,
          offset: 0,
        },
      },
      () => {
        this.fetchUsers()
      },
    )
  },
  /**
   * tab切换
   * @param e
   */
  changeType(e: any) {
    const {
      target: {
        dataset: { type },
      },
    } = e
    const {
      data: { type: oldType, followings, followers },
    } = this
    if (oldType !== type) {
      this.setData(
        {
          type,
        },
        () => {
          if (type === 'following' && followings.length === 0) {
            this.onPullDownRefresh()
          }
          if (type === 'follower' && followers.length === 0) {
            this.onPullDownRefresh()
          }
        },
      )
    }
  },

  /** 获取关注数据 */
  async fetchUsers(loadMore = false) {
    const {
      data: { type, loading },
    } = this
    const { data } = this
    if (loading) return
    let method = userApi.getUserFollowing,
      loadType = this.data.followingCanLoad,
      queryType = this.data.followingQuery,
      userType = this.data.followings,
      loadTypeName = 'followingCanLoad' as keyof typeof data,
      queryTypeName = 'followingQuery' as keyof typeof data,
      userTypeName = 'followings' as any,
      offset = this.data.followingQuery.offset
    if (type === 'follower') {
      method = userApi.getUserFans
      loadType = this.data.followerCanLoad
      queryType = this.data.followerQuery
      userType = this.data.followers
      loadTypeName = 'followerCanLoad'
      queryTypeName = 'followerQuery'
      userTypeName = 'followers'
      offset = this.data.followerQuery.offset
    }
    if (type === 'invitee') {
      loadType = this.data.inviteeCanLoad
      queryType = this.data.inviteeQuery
      userType = this.data.invitee
      loadTypeName = 'inviteeCanLoad'
      queryTypeName = 'inviteeQuery'
      userTypeName = 'invitee'
      offset = this.data[queryTypeName].offset
    }
    // 加载更多
    if (loadMore) {
      if (!loadType) {
        return
      }
    }
    const limit =
      type === 'invitee'
        ? this.data.inviteeQuery.limit
        : type === 'follower'
        ? this.data.followerQuery.limit
        : this.data.followingQuery.limit
    this.setData({ loading: true })
    const users =
      type === 'invitee'
        ? (
            await userApi.getInvitee({
              offset: loadMore ? offset : 0,
              limit: limit,
            })
          ).users
        : await method(0 as never, queryType)
    // 不能加载更多了
    if (users.length < limit) {
      this.setData({
        [loadTypeName]: false,
      })
    }
    this.setData({
      [queryTypeName]: {
        ...queryType,
        offset: (offset += users.length),
      },
    })
    if (loadMore) {
      this.setData({
        [userTypeName]: [...userType, ...users],
        loading: false,
      })
    } else {
      wx.stopPullDownRefresh()
      this.setData({
        [loadTypeName]: true,
        [userTypeName]: users,
        loading: false,
      })
    }
  },

  followAction(e: any) {
    const {
      target: {
        dataset: { user },
      },
    } = e
    const {
      data: { type },
    } = this
    const { data } = this
    let method = 'followUser' as keyof typeof userApi,
      has_follower = true,
      users = 'followings' as keyof typeof data
    // 已关注状态
    if (user.has_follower) {
      method = 'unFollowUser'
      has_follower = false
    }
    if (type === 'follower') {
      users = 'followers'
    } else if (type === 'invitee') {
      users = 'invitee'
    }
    userApi[method](user.id as never).then(() => {
      // 如果是在关注列表操作
      if (type === 'follower') {
        user.has_follower = has_follower
        const index = this.data.followers.findIndex((i: any) => i.id === user.id)
        const userList = this.data[users]
        this.data.followers[index].has_follower = has_follower

        // 删除或者添加关注列表中对应的数据
        const followingList = this.data.followings
        // 如果取消关注，则删除
        !has_follower &&
          followingList.splice(
            followingList.findIndex((i: DomoUser) => i.id === user.id),
            1,
          )
        // 关注则添加到第一个
        ;(has_follower && followingList.length) > 0 && followingList.unshift(user)
        this.setData({
          [users]: userList,
          followings: followingList,
        })
      }
      // 如果是在关注列表操作
      if (type === 'invitee') {
        user.has_follower = has_follower
        const index = this.data.invitee.findIndex((i: any) => i.id === user.id)
        const userList = this.data[users] as any
        userList[index].has_follower = has_follower

        this.setData({
          [users]: userList,
        })
      }
      // 取消关注后
      if (type === 'following' && !has_follower) {
        const followingList = this.data.followings
        const followerList = this.data.followers
        // 从关注列表中删除
        followingList.splice(
          followingList.findIndex((i) => i.id === user.id),
          1,
        )
        // 在粉丝列表中改变状态
        const index = followerList.findIndex((i) => i.id === user.id)
        index > -1 && (followerList[index].has_follower = has_follower)
        this.setData({
          followings: followingList,
          followers: followerList,
        })
      }
    })
  },
})
